/*
 * Copyright 2011 The Rusted Roof, LLC.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.proteusframework.platformservice;

import org.proteusframework.core.api.RuntimeEnvironment;
import org.proteusframework.core.api.model.IGlyphRenderer;
import org.proteusframework.core.api.model.INamespace;
import org.proteusframework.core.base.AbstractRuntimeEngine;
import org.proteusframework.core.util.Assert;
import org.proteusframework.platformservice.lifecycle.api.*;
import org.proteusframework.platformservice.persistence.api.IMessageBeanManager;
import org.proteusframework.platformservice.persistence.api.IPersistenceService;

import java.util.logging.Logger;

/**
 * Base class of all {@link IExtendedRuntimeEngine} instances.
 */
public abstract class AbstractExtendedRuntimeEngine extends AbstractRuntimeEngine
        implements IExtendedRuntimeEngine, ILifecycleListener, INamespace
{
    private static final Logger logger = Logger.getLogger(AbstractExtendedRuntimeEngine.class.getCanonicalName());

    protected ILifecycleService lifecycleService;

    protected INamespace namespace;

    /**
     * Constructs a runtime engine targeting the specified runtime environment, dynamically configured using a
     * {@link org.proteusframework.core.runtime.DefaultRuntimeConfiguration} that reads its configuration from a .properties file found on the CLASSPATH,
     * typically inside of the Proteus .jar file.
     *
     * @param namespace          Namespace for the runtime engine
     * @param runtimeEnvironment Target runtime environment
     */
    protected AbstractExtendedRuntimeEngine(INamespace namespace, RuntimeEnvironment runtimeEnvironment, IGlyphRenderer glyphRenderer)
    {
        super(runtimeEnvironment, glyphRenderer, new ExtendedRuntimeConfiguration());

        Assert.parameterNotNull(namespace, "Parameter 'namespace' must not be null");
        Assert.parameterNotNull(namespace.getFamily(), "Parameter 'namespace.getFamily() must not be null");
        Assert.parameterNotNull(namespace.getId(), "Parameter 'namespace.getId() must not be null");
        this.namespace = namespace;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getFamily()
    {
        return namespace.getFamily();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getId()
    {
        return namespace.getId();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getRefId()
    {
        return namespace.getRefId();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public IExtendedRuntimeConfiguration getExtendedRuntimeConfiguration()
    {
        return (IExtendedRuntimeConfiguration) runtimeConfiguration;
    }

    /**
     * {@inheritDoc}
     * <p/>
     * Default implementation takes no action
     */
    @Override
    public void onCustomPlatformServiceInitializationException(ServiceInitializationException e)
    {
        // Empty implementation
    }

    @Override
    protected void onDelegateInjected()
    {
        logger.info("onDelegateInjected() in AbstractExtendedRuntimeEngine");

        //
        // Automatically register the app as a lifecycle listener so that message registration is streamlined
        lifecycleService = delegate.adapt(IExtendedPlatformDelegate.class).getLifecycleService();
        lifecycleService.addLifecycleListener(this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onLifecycleEvent(LifecycleServiceIntentionEvent event)
    {
        // Empty
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onLifecycleEvent(LifecycleActivityEvent event)
    {
        if (event.getActivity() == LifecycleActivity.MessageBeanRegistration && event.getPhase() == LifecyclePhase.Pre)
        {
            IPersistenceService persistence = delegate.adapt(IExtendedPlatformDelegate.class).getPersistenceService();
            registerMessageBeans(persistence.narrow(IMessageBeanManager.class));
        }
    }

    /**
     * Applications must override this method and code their own unique message bean registration process. This callback
     * is invoked on the {@link org.proteusframework.platformservice.lifecycle.api.LifecyclePhase#Pre} {@link org.proteusframework.platformservice.lifecycle.api.LifecycleActivity#MessageBeanRegistration} lifecycle notification.
     *
     * @param messageBeanManager Primordial persistence service's message bean manager
     */
    protected abstract void registerMessageBeans(IMessageBeanManager messageBeanManager);
}
